//
//  HomePage-aboutMap.swift
//  Uber
//
//  Created by 朱 桓 on 16/1/24.
//  Copyright © 2016年 zhu.huan. All rights reserved.
//

import Foundation

class CarAnimationView: BMKAnnotationView {
    var imageView:UIImageView!
    
    override init!(annotation: BMKAnnotation!, reuseIdentifier: String!) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        
        self.bounds = CGRect(x: 0, y: 0, width: 32, height: 32)
        self.backgroundColor = UIColor.clearColor()
        
        imageView = UIImageView(image: UIImage(named: "map-taxi.png"))
        imageView.frame = self.bounds
        self.addSubview(imageView)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension HomePage:BMKLocationServiceDelegate, BMKGeoCodeSearchDelegate,BMKPoiSearchDelegate,BMKRouteSearchDelegate {
    /**
    *添加地图
    */
    func addBadiDuMap()
    {
        mapView = BMKMapView(frame: self.view.bounds)
        self.view.addSubview(mapView!)
        mapView?.zoomLevel = 14
        
        geoCode = BMKGeoCodeSearch()
        poiSearch = BMKPoiSearch()
        routeSearch = BMKRouteSearch()
        
        startLocation()
    }
    
    /**
    *开始定位服务
    */
    func startLocation()
    {
        locService = BMKLocationService()
        locService?.delegate = self
        locService?.startUserLocationService()
        
        mapView?.showsUserLocation = true
        
        userCorrdinate = CLLocationCoordinate2D(latitude: 40.115, longitude: 116.404)
    }
    
    /**
     *开始搜索服务
     */
    @IBAction func doSearch(sender:UIButton)
    {
        let option = BMKCitySearchOption()
        
        option.city = "北京南站"
        option.keyword = "北京南站"
        poiSearch?.poiSearchInCity(option)
    }
    
    /**
    *更新用户位置
    */
    func didUpdateBMKUserLocation(userLocation: BMKUserLocation!)
    {
        // 实时更新用户位置
//        userCorrdinate = userLocation.location.coordinate
//        //print(userCorrdinate)
//        mapView?.updateLocationData(userLocation)
        
        if !isMoveup! {
           self.addCars()
        }

        self.startTimer()
        //self.getCarArraiveTime()
    }
    
    /**
    *添加车辆在地图上
    */
    func addCars()
    {
        mapView?.removeOverlays(mapView?.overlays)
        
        // 更新车辆之前先删除之前的标记
        if point != nil {
            mapView?.removeAnnotation(point)
        }
        
        // 添加一个车辆（当用户位置发到服务端，服务端返回附近车辆的经纬度数组，循环添加车辆）
        point = BMKPointAnnotation()
        point?.coordinate = CLLocationCoordinate2D(latitude: userCorrdinate!.latitude+0.002, longitude: userCorrdinate!.longitude+0.002)
        point?.title = "Car"
        mapView?.addAnnotation(point)
    }
    
    /**
    *车辆绘制的代理函数
    */
    func mapView(mapView: BMKMapView!, viewForAnnotation annotation: BMKAnnotation!) -> BMKAnnotationView! {
        
       // print("annotation:\(annotation.coordinate)")
       let car = CarAnimationView(annotation: annotation, reuseIdentifier: "PID")
       // let car = BMKAnnotationView(annotation: annotation, reuseIdentifier: "PID")
        // 不支持拖拽
        car.draggable = false
        
        return car
    }
    
    /**
    *启动更新车辆定时器
    */
    func startTimer()
    {
        timer = NSTimer(timeInterval: 1, target: self, selector: "updateCars", userInfo: nil, repeats: true)
        timer?.fire()
    }
    
    /**
    *删除定时器
    */
    func stopTimer()
    {
        timer?.invalidate()
    }
    
    /**
    *更新当前用户位置
    */
    func updateCars()
    {
        userCorrdinate!.latitude += 0.0002
        userCorrdinate!.longitude += 0.0002
    }
    
    /**
    *计算车辆到达时间
    *描述：point1 车辆的坐标，point2 用户目前坐标 请求指定车辆的车速，服务端下发过来
    */
    func getCarArraiveTime()
    {
        let point1 = BMKMapPointForCoordinate(CLLocationCoordinate2DMake(39.915,116.404));
        let point2 = BMKMapPointForCoordinate(CLLocationCoordinate2DMake(38.915,115.404));
        // 两个点的距离
        let distance = BMKMetersBetweenMapPoints(point1,point2);
        
        // 时间 = 距离/车速 (车速服务端传过来的)
        let time = distance / (50*1000)
        print(time)
    }

    /**
     *反地理编码
     */
    func mapView(mapView: BMKMapView!, regionDidChangeAnimated animated: Bool) {
        let point  = mapView.convertPoint(tuDingBtn!.center, toCoordinateFromView: self.view)
        print(point)
        
        let option  = BMKReverseGeoCodeOption()
        option.reverseGeoPoint = point
        geoCode?.reverseGeoCode(option)
    }
    
    /**
     *反地理编码后返回的结果
     */
    func onGetReverseGeoCodeResult(searcher: BMKGeoCodeSearch!, result: BMKReverseGeoCodeResult!, errorCode error: BMKSearchErrorCode) {
        self.searchAdd?.text = result.address
    }
    
    /**
    *返回POI搜索结果
    *@param searcher 搜索对象
    *@param poiResult 搜索结果列表
    *@param errorCode 错误号，@see BMKSearchErrorCode
    */
    func onGetPoiResult(searcher: BMKPoiSearch!, result poiResult: BMKPoiResult!, errorCode: BMKSearchErrorCode) {
        
        mapView?.removeAnnotations(mapView?.annotations)
        
        if errorCode == BMK_SEARCH_NO_ERROR {
            // 存放附近区域的所有点的经纬度
            var annotations:[BMKPointAnnotation] = []
            for (var i = 0; i < poiResult.poiInfoList.count; ++i)
            {
                let poi = poiResult.poiInfoList[i]
                let item = BMKPointAnnotation()
                
                item.coordinate = poi.pt
                item.title = poi.name
                
                annotations.insert(item, atIndex: i)
            }
            
            //添加多个标注
            mapView?.addAnnotations(annotations)
            //设置地图使显示区域显示所有annotations
            mapView?.showAnnotations(annotations, animated: true)
            
        } else {
            ptLog("onGetPointResult Error")
        }
    }
    
    /**
     *车辆轨迹实现
     */
    @IBAction func dosearchRoute(sender:UIButton)
    {
        // 发起检索
        let start = BMKPlanNode()
        start.name = "龙泽"

        let end = BMKPlanNode()
        end.name = "西单"
        
        let routeOption = BMKTransitRoutePlanOption()
        
        routeOption.city = "北京市"
        routeOption.from = start
        routeOption.to = end
        
        let flag = routeSearch?.transitSearch(routeOption)
        
        if flag == true {
            ptLog("bus 检索发送成功")
        } else {
            ptLog("bus 检索发送失败")
        }
    }
    
    /**
    *返回公交搜索结果
    *@param searcher 搜索对象
    *@param result 搜索结果，类型为BMKTransitRouteResult
    *@param error 错误号，@see BMKSearchErrorCode
    */
    func onGetTransitRouteResult(searcher: BMKRouteSearch!, result: BMKTransitRouteResult!, errorCode error: BMKSearchErrorCode)
    {
        if error == BMK_SEARCH_NO_ERROR {
            ptLog("轨迹成功")
        } else {
            ptLog("轨迹失败")
        }
    }
    
}
